/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package construtora.limiar.servlet;

import construtora.limiar.constants.Papeis;
import construtora.limiar.dao.ClienteDAO;
import construtora.limiar.dao.ImovelDAO;
import construtora.limiar.mensagens.Message;
import construtora.limiar.models.Endereco;
import construtora.limiar.models.Imovel;
import construtora.limiar.models.Usuario;
import construtora.limiar.models.generic.AbstractCliente;
import construtora.limiar.util.AuthorizationController;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author michel
 */
@WebServlet(name = "ImovelSlt", urlPatterns = {"/ImovelSlt"})
public class ImovelSlt extends AuthSlt {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        operacao = request.getParameter("operacao");
        chave = request.getParameter("chave");
        RequestDispatcher rd = null;
        
        String[] ESTADOS = new String[]{"AC","AL","AP","AM","BA","CE","DF","ES","GO","MA","MT","MS","MG","PA","PB","PR","PE","PI","RR","RO","RJ","RN","RS","SC","SP","SE","TO"};
        /*
        RequestDispatcher rd = null;
        
        Usuario usuario = (Usuario) getServletContext().getAttribute("usuario");
        AuthorizationController ac = AuthorizationController.getInstance(usuario.getApelido());
        
        if (!ac.hasRole(new String[]{Papeis.GRAVADOR,Papeis.ADMINISTRADOR})){
            Message.setLastInfo("Você não tem permissão para usar este recurso!");
            response.sendRedirect("admin.jsp");
            return;
        }
        
        String cadastro = request.getParameter("cadastro");
        String retornar = request.getParameter("retornar");
        if (retornar != null) {
            response.sendRedirect("cadastro.jsp?cadastro=" + cadastro);
            return;
        }
        if (request.getCharacterEncoding() == null)
            request.setCharacterEncoding("UTF-8");
            */
        
        if("incluir".equals(operacao)){
            try
                {
                    ClienteDAO  dao = new ClienteDAO();
                    AbstractCliente cliente = new AbstractCliente() {

                        @Override
                        public String getIdentificacao() {
                            throw new UnsupportedOperationException("Not supported yet.");
                        }

                        @Override
                        public void setIdentificacao(String identificacao) {
                            throw new UnsupportedOperationException("Not supported yet.");
                        }

                        @Override
                        public String getDocumento() {
                            throw new UnsupportedOperationException("Not supported yet.");
                        }

                        @Override
                        public void setDocumento(String documento) {
                            throw new UnsupportedOperationException("Not supported yet.");
                        }
                    };
                    
                    cliente.setId(Integer.parseInt(chave));
                    
                    cliente = (AbstractCliente) dao.fetchOne(cliente);
                    
                    //Endereco endereco = cliente.getEndereco();
                    //request.setAttribute("endereco",endereco);
                    request.setAttribute("ESTADOS", ESTADOS);
                    request.setAttribute("cliente",cliente);
                    rd = request.getRequestDispatcher("/gravarImovel.jsp");
                }
            catch(Exception e)
                {
                    e.printStackTrace();
                }
            
        }else if(("gravar".equals(operacao)) || ("novo".equals(operacao))){
            
            Imovel imovel = new Imovel();
            Endereco endereco = new Endereco();
        
            AbstractCliente cliente = new AbstractCliente() {

                @Override
                public String getIdentificacao() {
                    throw new UnsupportedOperationException("Not supported yet.");
                }

                @Override
                public void setIdentificacao(String identificacao) {
                    throw new UnsupportedOperationException("Not supported yet.");
                }

                @Override
                public String getDocumento() {
                    throw new UnsupportedOperationException("Not supported yet.");
                }

                @Override
                public void setDocumento(String documento) {
                    throw new UnsupportedOperationException("Not supported yet.");
                }
            };
            cliente.setId(Integer.parseInt(request.getParameter("id_cliente")));
            imovel.setCliente(cliente);
            imovel.setEndereco((Endereco) gravarEndereco(request, endereco));
            imovel.setMetragem(Double.parseDouble(request.getParameter("metragem")));
            ImovelDAO dao = new ImovelDAO();
            if(imovel.getId() == null){
                dao.insert(imovel);
                imovel.setId(dao.getLast(imovel));
            }else{
                dao.update(imovel);
            }
            if ("novo".equals(operacao)) {                
                rd = request.getRequestDispatcher("/construtora-limiar/ImovelSlt?operacao=incluir&chave="+cliente.getId());
            } else {
                rd = request.getRequestDispatcher("ClienteSlt?operacao=listar&chave="+cliente.getId());
            }
            
        }else if("editar".equals(operacao)){
            //
        }else if("gravaralteracao".equals(operacao)){
            //
        }else if("listar".equals(operacao)){
            //
        }else if("excluir".equals(operacao)){
            //
        }
        if(rd != null)
            rd.forward(request, response);

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
